<template>
  <div ref="chart" style="width: 100%; height: 400px"></div>
</template>

<script lang="ts" setup>
import { onMounted, onBeforeUnmount, defineProps, ref, watch } from "vue";
import * as echarts from "echarts";
const props = defineProps<{ pieProportionData: any[] }>();
// 创建一个引用来绑定 DOM 元素
const chart = ref(null);
let pieProportionChart: echarts.ECharts | null = null;

// 注册生命周期钩子
onBeforeUnmount(() => {
  if (pieProportionChart) {
    window.removeEventListener("resize", resizeChart);
    pieProportionChart.dispose();
    pieProportionChart = null; // 清除引用
  }
});

const resizeChart = () => {
  pieProportionChart?.resize();
};


const initChart = () => {
  // 先销毁已有实例，避免重复初始化
  if (pieProportionChart) {
    pieProportionChart.dispose();
  }

  pieProportionChart = echarts.init(chart.value);

  const option = {
    title: {
      text: "消费类名占比",
      left: "left",
    },
    tooltip: {
      trigger: "item",
    },
    legend: {
      orient: "vertical",
      right: 10,
      top: 20,
      bottom: 20,
    },
    series: [
      {
        name: "消费占比",
        type: "pie",
        radius: ["40%", "70%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: false,
          position: "center",
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 40,
            fontWeight: "bold",
          },
        },
        labelLine: {
          show: false,
        },
        data: props.pieProportionData,
      },
    ],
  };

  pieProportionChart.setOption(option);

  window.addEventListener("resize", resizeChart);
};

onMounted(initChart);

watch(() => props.pieProportionData, initChart, { deep: true });
</script>

<style scoped></style>
